const fs = require("fs");
const path = require("path");
const { exec } = require("child_process");
const gulp = require("gulp");
const uglify = require("gulp-uglify");
const jsonmin = require("gulp-jsonmin");

const rootPath = path.resolve("./src");

const filePath = path.resolve("./dist/tsc");
var del = require("del");

const { src, dest, series } = gulp;

// tsc 转译之后 gulp 打包压缩js
function jsToDist(dir, dirout) {
	src(`${dir}/*.js`)
		.pipe(uglify())
		.pipe(dest(`${dirout}/`));
}

// 处理项目中的 json 文件
function jsonToDist(dir, dirout) {
	src([`${dir}/*.json`])
		.pipe(jsonmin())
		.pipe(dest(`${dirout}/`));
}

// 处理项目中的静态文件
function fileToDist(dir, dirout) {
	src([`${dir}/*`]).pipe(dest(`${dirout}/`));
}

//文件遍历方法
function fileDisplay(filePath, dir, dirout, callback, info = false) {
	callback(dir, dirout);
	fs.readdir(filePath, function (err, files) {
		if (err) {
		} else {
			files.forEach(function (filename) {
				const filedir = path.join(filePath, filename);
				fs.stat(filedir, function (eror, stats) {
					if (eror) {
					} else {
						const isDir = stats.isDirectory();
						const isFile = stats.isFile();
						const nextdir = `${dir}\\${filename}`;
						if (isFile && nextdir.startsWith("src") && info) {
							console.log(`Build File: ${dir}\\${filename}`);
						}
						if (isDir) {
							const nextdirout = `${dirout}\\${filename}`;
							fileDisplay(filedir, nextdir, nextdirout, callback, info);
						}
					}
				});
			});
		}
	});
}


function tscBuild(cb) {
    del.sync(["dist"]);
    // 执行 tsc 编译 tsc-alias 处理路径别名
    return exec("tsc -p tsconfig.json && tsc-alias");
}

function copyFile(cb) {
    src(`package.json`).pipe(dest(`dist/`));
    const binPath = path.resolve("./src/bin");
    const publicPath = path.resolve("./src/public");
	fileDisplay(filePath, "dist\\tsc", "dist", jsToDist);
	fileDisplay(rootPath, "src", "dist", jsonToDist);
	fileDisplay(publicPath, "src\\public", "dist\\public", fileToDist);
	fileDisplay(binPath, "src\\bin", "dist\\bin", fileToDist);
	fileDisplay(rootPath, "src", "dist", jsToDist, true);
	cb();
}

exports.default = series(tscBuild, copyFile);